package com.ybchen.content;

import com.alibaba.ttl.TransmittableThreadLocal;
import org.slf4j.MDC;

import java.util.UUID;

/**
 * @description: traceId上下文
 * @author: alex
 * @create: 2024-10-20 20:18
 */
public class TraceContextHolder {
    private static final ThreadLocal<String> traceId = new TransmittableThreadLocal<>();

    public static void setTraceId() {
        String tempTraceId = getTraceId();
        if (tempTraceId == null || "".equals(tempTraceId)) {
            tempTraceId = UUID.randomUUID().toString();
        }
        traceId.set(tempTraceId);
        MDC.put("traceId", tempTraceId);
    }

    private static String getTraceId() {
        return traceId.get();
    }

    public static void clear() {
        traceId.remove();
        MDC.remove("traceId");
    }
}
